#include "index.hpp"
#include <algorithm>
#include <jsoncpp/json/json.h>

namespace ns_searcher{

    struct InvertedElementPrint{
        uint64_t doc_id;
        int weight;
        std::vector<std::string> words;
        InvertedElementPrint(): doc_id(0), weight(0) {}
    };

    class Searcher{
    private:
        ns_index::Index* index;
    public:
        Searcher() {}
        ~Searcher() {}
    public:
        void InitSearcher(const std::string& input)
        {
            // 获取index对象
            index = ns_index::Index::GetInstance();
            std::cout << "获取index单例成功!" << std::endl;
            // 建立索引
            index->BuildIndex(input);
            std::cout << "建立正排和倒排索引成功!" << std::endl;
        }
        void Search(const std::string query, std::string* json_string)
        {
            // 分词
            std::vector<std::string> words;
            ns_util::JiebaUtil::CutString(query, &words);
            // 触发
            // ns_index::InvertedList inverted_list_all;
            std::vector<InvertedElementPrint> inverted_list_all;
            std::unordered_map<uint64_t, InvertedElementPrint> tokens_map;

            for(std::string& word : words)
            {
                boost::to_lower(word);

                ns_index::InvertedList* inverted_list = index->GetInvertedList(word);
                if(nullptr == inverted_list)
                {
                    continue;
                }
                // inverted_list_all.insert(inverted_list_all.end(), inverted_list->begin(), inverted_list->end());
                for(const auto& elem : *inverted_list)
                {
                    auto& item = tokens_map[elem.doc_id]; // 找到分词相同的文档元素
                    item.doc_id = elem.doc_id;
                    item.weight += elem.weight;
                    item.words.push_back(elem.word);
                }
            }
            for(const auto& item : tokens_map)
            {
                inverted_list_all.push_back(std::move(item.second));
            }
            // 合并排序
            // std::sort(inverted_list_all.begin(), inverted_list_all.end(),\
            //     [](const ns_index::InvertedElem& e1, const ns_index::InvertedElem& e2)
            //     {return e1.weight > e2.weight;});
            std::sort(inverted_list_all.begin(), inverted_list_all.end(),\
                 [](const InvertedElementPrint& e1, const InvertedElementPrint& e2)
                 {return e1.weight > e2.weight;
                 });

            // 构建
            Json::Value root;
            for(auto& item : inverted_list_all)
            {
                ns_index::DocInfo* doc = index->GetForwardIndex(item.doc_id);
                if(nullptr == doc)
                {
                    continue;
                }
                // json
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->contnet, item.words[0]); // 实际需要摘要, 暂
                elem["url"] = doc->url;

                root.append(elem);
            }

            // Json::StyledWriter writer; for debug
            Json::FastWriter writer; // for release
            *json_string = writer.write(root);
        }

        std::string GetDesc(const std::string& html_content, const std::string& word)
        {
            const int pre_step = 50;
            const int next_step = 100;
            // 找到首次出现
            auto it = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(), [](int x, int y){
                return (std::tolower(x) == std::tolower(y));
                });
            if(it == html_content.end()) return "None";

            int pos = std::distance(html_content.begin(), it);
            int start = 0, end = html_content.size() - 1;
            if(pos > start + pre_step) start = pos - pre_step;
            if(pos < end - next_step) end = pos + next_step; // (int)pos < (int)(end - next_step()
            
            if(start >= end) return "None";
            std::string desc = html_content.substr(start, end - start);
            desc += "...";
            return desc;
        }
    };
}